<?php defined('BASEPATH') or exit('No direct script access allowed');

/**
 * Class Trips_client_model
 */
class Trips_trips_model extends CI_Model
{
    /**
     * @var
     */
    private $table;

    /**
     * @var
     */
    private $table_sec;

    /**
     * @var
     */
    private $table_dist;
    private $sid ;

    /**
     *
     */
    public function __construct()
    {
        parent::__construct();
        $this->sid = $GLOBALS['sid'];
        $this->table      = $this->db->dbprefix("trips");
        $this->table_sec  = $this->db->dbprefix("trips_category");
        $this->table_dist = $this->db->dbprefix("trips_dist");
    }

    public function ingore_others()
    {
        return in_array(SITEID,array('32765','33002', '32967'));
    }

    /**
     * 批量添加分类
     *
     * @param $new_category
     * @return bool
     */
    public function category_multi_add( $new_category)
    {
        if(empty($new_category))
        {
            return FALSE;
        }
        $row = array();
        foreach ($new_category as $key => $value)
        {
            if(empty($value['n']))
            {
                continue;
            }
            $row[$key]['name'] = $value['n'];
            $row[$key]['description']   = $value['d'];
        }

        if($row)
        {
            return $this->db->insert_batch($this->table_sec, $row);
        }
        return FALSE;
    }

    public function category_sub_multi_add($new_sub_category)
    {
        if(empty($new_sub_category))
        {
            return FALSE;
        }
        $row = array();
        $i = 0;

        foreach ($new_sub_category as $pid => $children)
        {
            if(empty($children['n']))
            {
                continue;
            }

            foreach($children['n'] as $index => $child)
            {
                if(empty($child)){
                    continue;
                }
                $row[$i]['name']        = $child;
                $row[$i]['description'] = $children['d'][$index];
                $row[$i]['parent_id']   = $pid;
                $i ++;
            }
        }
        if($row)
        {
            return $this->db->insert_batch($this->table_sec, $row);
        }
        return FALSE;
    }

    /**
     * 增加分类
     *
     * @param array $row
     * @return bool
     */
    public function category_add(array $row)
    {
        if($this->db->insert($this->table_sec, $row))
        {
            return $this->db->insert_id();
        }
        return FALSE;
    }


    /**
     * @param string $where
     * @return array
     */
    public function category_list($where = '')
    {
        if($where){
            $where = ' WHERE ' . $where;
        }
        $retval = array();
        $query = $this->db->query("SELECT * FROM {$this->table_sec} $where ORDER BY id ASC");
        if ($query->num_rows() > 0) {
            $retval = $query->result_array();
        }
        return $retval;
    }

    /**
     * 检查子类是否有攻略，有返回数组，无返回空数组
     *
     * @param $pid
     * @return array
     */
    public function category_trips_by_pid($pid)
    {
        $retval = array();
        $query = $this->db->query("SELECT id FROM {$this->table_sec} WHERE parent_id=? AND trips_count>0", array($pid));
        if ($query->num_rows() > 0)
        {
            $retval = $query->result_array();
        }
        return $retval;
    }

    /**
     * 读取一个完整的分类信息
     *
     * @param $id
     * @return array
     */
    public function category_by_id($id)
    {
        static $category = array();
        if(isset($category[$id])){
            return $category[$id];
        }
        $retval = array('name'=>'');
        $query = $this->db->query("SELECT * FROM {$this->table_sec} WHERE id=? LIMIT 1", array($id));
        if ($query->num_rows() > 0)
        {
            $retval = $query->row_array();
        }
        $category[$id] = $retval;
        return $retval;
    }

    /**
     * 删除分类
     *
     * @param $id_array
     * @return bool
     */
    public function category_delete($id_array)
    {
        if(empty($id_array) || !is_array($id_array)){
            return FALSE;
        }
        /*检查自己或子类有没攻略，有不删*/
        foreach ($id_array as $id) {
            if($this->category_trips_by_pid($id)){
                continue;
            }
            $this->db->delete(
                $this->table_sec,
                array(
                'id'          => $id,
                'trips_count' => 0,
            ));
        }
        return TRUE;
    }

    /**
     * @param array $row
     * @return mixed
     */
    public function category_update(array $row)
    {
        $id = $row['id'];
        unset($row['id']);
        return $this->db->update($this->table_sec, $row, array('id' => $id));
    }

    /**
     * @param array $data
     * @return bool
     */
    public function trips_add(array $data)
    {
        $data['crts'] = time();
        $data['upts'] = time();
        $continent = $data['continent'];
        $country   = $data['country'];
        $province  = $data['province'];
        $city      = $data['city'];
        $area      = $data['area'];
        unset($data['continent'], $data['country'], $data['province'], $data['city'], $data['area']);

        if($this->db->insert($this->table, $data))
        {
            $id = $this->db->insert_id();
            if($id){
                $this->__build_batch_dist($id, $continent, $country, $province, $city, $area);
            }
            if($data['category'] && $id)
            {
                $this->db->query(
                    "UPDATE $this->table_sec SET trips_count=trips_count+1 WHERE id =?",
                    array($data['category'])
                );
            }
            return $id;
        }
        return FALSE;
    }

    /**
     * @param $id
     * @param array $data
     * @return bool
     */
    public function trips_edit($id, array $data)
    {
        $data['upts'] = time();

        @$continent = $data['continent'];
        @$country   = $data['country'];
        @$province  = $data['province'];
        @$city      = $data['city'];
        @$area      = $data['area'];
        unset($data['continent'], $data['country'], $data['province'], $data['city'], $data['area']);

        if($this->db->update($this->table, $data, array('id' => $id)))
        {
            $this->__build_batch_dist($id, $continent, $country, $province, $city, $area, TRUE);
            return TRUE;
        }
        return FALSE;
    }

    /**
     * @param int $id
     * @return bool
     */
    public function trips_del($id)
    {
        if($this->db->update($this->table, array('status' => -1), array('id' => $id)))
        {
            return TRUE;
        }
        return FALSE;
    }

    /**
     * @param int $page_size
     * @param int $now_page
     * @param string $where
     * @return array
     */
    public function trips_list($page_size=20,$now_page=1,$where = '',$extra='', $order = '')
    {
        $fields = 'sid,id,category,from,author,file_url,subject,keywords,description,abstract,cruser,upuser,crts,upts,view,status';
        $this->db->select($fields);
        if($extra || $this->ingore_others())
        {
            if(is_string($where)){
                $where .= " and sid = $this->sid " ;
            }else if(is_array($where)){
                $where['sid'] = $this->sid;
            }
        }
        if($order){
            $this->db->order_by($order);
        }
        if(!empty($where))$this->db->where($where, NULL, FALSE);
        $query = $this->db->get($this->table,$page_size,($now_page-1)*$page_size);
        $data = array();
        $ids = array();



        foreach($query->result_array() as $row){
            $row['category_row'] = $this->category_by_id($row['category']);
            $data[] = $row;
            if(!$row['crts'] && !$row['upts']){
                $row['crts'] =$row['upts'] = time()-999999;
            }else if(!$row['crts'] && $row['upts']){
                $row['crts'] =$row['upts'];
            }else{
                $row['upts'] =$row['crts'];
            }
            $ids[] = $row['id'];
        }

        if($ids){
            $dist = $this->get_dist($ids);
        }
        foreach ($data as $k => $v)
        {
            $data[$k]['dist'] = isset($dist[$v['id']]) ? $dist[$v['id']] : array();
        }
        return $data;
    }

    /**
     * @param int $page_size
     * @param int $now_page
     * @param string $where
     * @param string $extra  1表示只取本站
     * @return array
     */
    public function trips_list_2($page_size=20,$now_page=1,$where = '',$extra='')
    {
        $fields = "$this->table.id,$this->table.author,$this->table.subject,$this->table.file_url,$this->table.abstract,$this->table.crts";
        $this->db->select($fields);
        $table_query = '';

        $dist  = false ;
        if(isset($where['province'])&&!empty($where['province'])){
            $table_query .= " AND ".$this->table_dist.".province=$where[province]";
            $dist = true ;
        }

        if($extra || $this->ingore_others())
        {
            $table_query .= " AND ".$this->table.".sid = $this->sid";
        }

        if(isset($where['city'])&&!empty($where['city']))
        {
            $table_query .= " AND ".$this->table_dist.".city=$where[city]" ;
            $dist = true ;
        }

        if($dist)
        {
            $this->db->join($this->table_dist,$this->table_dist.".tid=$this->table.id ".$table_query,'inner');
        }

        $condition = "$this->table.status = '0'" ;
        if(isset($where['category'])&&!empty($where['category'])){

            $condition .= " AND $this->table.category = $where[category]";
        }

        if($this->ingore_others() || (isset($where['sid'])&&!empty($where['sid']))){

            $condition .= " AND $this->table.sid = ".SITEID;
        }

        if(isset($where['pic'])&&!empty($where['pic'])){

            $condition .= " AND ".$this->table.".file_url <> ''";
        }
        if($where['keywords']){
            $condition .= " AND $this->table.subject like'%".$where['keywords']."%' ";
        }

        $this->db->where($condition);
        $order_by = "trips.view desc,trips.id desc" ;
        if(isset($where['extra'])&&!empty($where['extra'])){

            if($where['extra']==0)
            {
                $order_by = "trips.view desc,trips.id desc" ;
            }
            if($where['extra']==1)
            {
                $order_by = "trips.upts desc,trips.id desc" ;
            }

        }

        $this->db->order_by($order_by);
        $query = $this->db->get($this->table,$page_size,($now_page-1)*$page_size);
        $data = array();
        $ids = array();
        foreach($query->result_array() as $row){
//            $row['category_row'] = $this->category_by_id($row['category']);
            if(!$row['crts'] && !$row['upts']){
                $row['crts'] =$row['upts'] = time()-999999;
            }else if(!$row['crts'] && $row['upts']){
                $row['crts'] =$row['upts'];
            }else{
                $row['upts'] =$row['crts'];
            }
            $data[] = $row;
//            $ids[] = $row['id'];
        }
//        if($ids){
//            //$dist = $this->get_dist($ids);
//        }

//        foreach ($data as $k => $v)
//        {
////            $data[$k]['dist'] = isset($dist[$v['id']]) ? $dist[$v['id']] : array();
//        }


        return $data;
    }


    public function trips_count_2($where = '',$extra='')
    {
        $fields = "count(*) AS total";
        $this->db->select($fields);
        $table_query = "";
        $dist  = false ;
        if(isset($where['province'])&&!empty($where['province'])){
            $table_query .= " AND ".$this->table_dist.".province=$where[province]";
            $dist = true ;
        }
        if(isset($where['city'])&&!empty($where['city'])){
            $table_query .= " AND ".$this->table_dist.".city=$where[city]" ;
            $dist = true ;
        }

        if($dist)
        {
            $this->db->join($this->table_dist,$this->table_dist.".tid=$this->table.id ".$table_query,'inner');
        }
        $condition = "$this->table.status = '0'" ;

        if(isset($where['category'])&&!empty($where['category'])){
            $condition .= " AND $this->table.category = $where[category]";
        }
        if($extra || $this->ingore_others()||$where['sid']){

            $condition .= " AND $this->table.sid = ".SITEID;
        }
        if($where['keywords']){
            $condition .= " AND $this->table.subject like'%".$where['keywords']."%' ";
        }


        $this->db->where($condition);
        $query = $this->db->get($this->table);
        $row = $query->row_array();
        return $row['total'];
    }

    public function trips_count($where = '',$extra='')
    {
        $this->db->select('count(*) AS total');
        if($extra  || $this->ingore_others())
        {
            $where .= " AND sid = $this->sid " ;
        }
        if(!empty($where))$this->db->where($where, NULL, FALSE);
        $query = $this->db->get($this->table);
        $row = $query->row_array();
        return $row['total'];
    }

    public function get_trips_by_id($id)
    {
        $where = array(
            'id' => $id
        );
        $this->db->select('*');
        if(!empty($where))$this->db->where($where, NULL, FALSE);
        $query = $this->db->get($this->table);

        $row = $query->row_array();
        if(empty($row))
        {
            return array();
        }

        $this->db->query("UPDATE $this->table SET `view`=`view`+1 WHERE id=$id");
        $row['category_row'] = $this->category_by_id($row['category']);
        $dist = $this->get_dist(array($row['id']));
        @$row['dist'] = $dist[$row['id']];

        return $row;
    }

    /**
     * @param $id
     * @param array $continent
     * @param array $country
     * @param array $province
     * @param array $city
     * @param bool $replace
     * @return mixed
     */
    private function __build_batch_dist($id, $continent, $country, $province, $city, $area, $replace = FALSE)
    {
        if($replace)
        {
            $this->db->delete($this->table_dist, array('tid' => $id));
        }
        $batch = array();
        if(!empty($continent))
        {
            foreach ($continent as $k => $v) {
                $batch[$k] = array(
                    'tid'       => $id,
                    'continent' => $v,
                    'country'   => $country[$k],
                    'province'  => $province[$k],
                    'city'      => $city[$k],
                    'area'      => $area[$k]
                );
            }
            return $this->db->insert_batch($this->table_dist, $batch);
        }
    }

    public function get_dist($ids = array())
    {
        if(!$ids){
            return array();
        }
        $this->db->select('*');
        $this->db->where_in(array(
            'tid' => $ids
        ), NULL, FALSE);
        $query = $this->db->get($this->table_dist);
        $data = array();
        foreach ($query->result_array() as $row)
        {
            $tid = $row['tid'];
            unset($row['id'], $row['tid']);
            $data[$tid][] = $row;
        }
        return $data;
    }

    /**
     * 获取前台农家乐列表页面
     * @param int $page_size 每页显示数目
     * @param int $now_page     显示第几页
     * @param  $where 查询条件
     * @return arrayarray
     */
    public function get_index_trips_list($page_size=10,$now_page=1,$where=array()){

        //农家乐ID
        $parent_id = $where['parent_id'];

        $fields = $this->table.'.id,'.$this->table.'.file_url,'.$this->table.'.subject,'.$this->table.'.abstract';
        $this->db->select($fields);

        //区域ID选择
        if(isset($where['area_id'])&&!empty($where['area_id'])){
            $this->db->join($this->table_dist, $this->table_dist.".tid=$this->table.id AND ".$this->table_dist.".area=$where[area_id]",'inner');
        }

        //特色选择ID
        if(isset($where['cat_id'])&&!empty($where['cat_id'])){
            $this->db->join($this->table_sec, $this->table_sec.".id=$this->table.category AND ".$this->table.".category=$where[cat_id] AND ".$this->table_sec.".parent_id=$parent_id",'inner');
        }else{
            $this->db->join($this->table_sec, $this->table_sec.".id=$this->table.category AND ".$this->table_sec.".parent_id=$parent_id",'inner');
        }
        //显示
        $this->db->where($this->table.'.status',0);

        $query = $this->db->get($this->table,$page_size,($now_page-1)*$page_size);
        $data = array();
        foreach($query->result_array() as $row){
            $row['file_url'] = empty($row['file_url'])?'static/public/images/nophoto.jpg':get_thumb($row['file_url']);
            $row['url'] = site_url('nongjiale/'.$row['id'].'.html');
            $data[] = $row;
        }
        return $data;
    }

    /**
     * 获取农家乐总数目
     * @param array $where
     * @return mixed
     */
    public function get_index_count($where = array())
    {
        //农家乐ID
        $parent_id = $where['parent_id'];

        //区域ID选择
        if(isset($where['area_id'])&&!empty($where['area_id'])){
            $this->db->join($this->table_dist, $this->table_dist.".tid=$this->table.id AND ".$this->table_dist.".area=$where[area_id]",'inner');
        }

        //特色选择ID
        if(isset($where['cat_id'])&&!empty($where['cat_id'])){
            $this->db->join($this->table_sec, $this->table_sec.".id=$this->table.category AND ".$this->table.".category=$where[cat_id] AND ".$this->table_sec.".parent_id=$parent_id",'inner');
        }else{
            $this->db->join($this->table_sec, $this->table_sec.".id=$this->table.category AND ".$this->table_sec.".parent_id=$parent_id",'inner');
        }

        //显示
        $this->db->where($this->table.'.status',0);
        $this->db->select('count(*) AS total');
        $query = $this->db->get($this->table);
        $row = $query->row_array();

        return $row['total'];
    }

    /**
     * 获取前台农家乐特色列表
     * @param array $where
     * @return array
     */
    public function get_index_cat_list($where){
        $cat_id = $where['parent_id'];
        $this->db->where('parent_id',$cat_id);
        $this->db->select('id,name');
        $query = $this->db->get($this->table_sec);
        $data = array();
        foreach($query->result_array() as $row){
            $data[] = $row;
        }
        return $data;
    }

    /**
     * 获取地区信息
     * @param $where
     * @return mixed
     */
    public function get_index_area_list($where){
        $parent_id = $where['parent_id'];
        $this->db->join($this->table_sec, $this->table_sec.".id=$this->table.category AND ".$this->table_sec.".parent_id=$parent_id",'inner');
        $this->db->join($this->table_dist, $this->table_dist.".tid=$this->table.id",'inner');
        $this->db->select("distinct($this->table_dist.area) as area");
        $query = $this->db->get($this->table);
        $row = $query->result_array();
        return $row;
    }

    /**
     * 获取前台农家乐详情
     * @param $id 主键ID
     * @param string $field 输出字段
     * @return mixed 返回值
     */
    public function get_index_info($id,$field='*'){
        if(!empty($field))$this->db->select($field);
        $this->db->where('id',$id);
        $query = $this->db->get($this->table);
        $row = $query->row_array();
        return $row;
    }

    /**
     * 根据条件获取攻略信息
     * @param array $trip_ids
     * @return array
     */
    public function get_list($trip_ids = array(),$fields="*")
    {
        if(empty($trip_ids)){
            return array();
        }
        $fields = 'sid,id,category,from,author,file_url,subject,keywords,description,abstract,cruser,upuser,crts,upts,view,status';
        $this->db->select($fields);
        $this->db->where_in('id',$trip_ids);
        $query = $this->db->get($this->table);
        $data = array();
        $ids = array();
        foreach($query->result_array() as $row){
            $row['category_row'] = $this->category_by_id($row['category']);
            $data[] = $row;
            $ids[] = $row['id'];
        }

        if($ids){
            $dist = $this->get_dist($ids);
        }
        foreach ($data as $k => $v)
        {
            $data[$k]['dist'] = isset($dist[$v['id']]) ? $dist[$v['id']] : array();
        }
        return $data;
    }
}
